﻿using LPP.Entity.ChatMessage;
using LPP.Entity.ChatMessageDto;
using LPP.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;

namespace LPP.Service.ChatService
{
    public class ChatService : IChatService
    {
        private readonly SqlDbContext _context;

        public ChatService(SqlDbContext context)
        {
            _context = context;
        }

        public async Task<bool> SaveMessageAsync(ChatMessage message)
        {
            try
            {
                message.MessageId = Guid.NewGuid();
                message.SendTime = DateTime.UtcNow;
                message.IsRead = false;

                await _context.ChatMessages.AddAsync(message);
                await _context.SaveChangesAsync();
                return true;
            }
            catch
            {
                return false;
            }
        }

        public async Task<List<ChatMessageDto>> GetChatHistoryAsync(string userId, string workerId)
        {
            var userIdInt = int.Parse(userId);
            var workerIdInt = int.Parse(workerId);

            return await _context.ChatMessages
                .Include(m => m.Sender)
                .Include(m => m.Receiver)
                .Where(m => (m.SenderId == userIdInt && m.ReceiverId == workerIdInt) ||
                           (m.SenderId == workerIdInt && m.ReceiverId == userIdInt))
                .OrderByDescending(m => m.SendTime)
                .Select(m => new ChatMessageDto
                {
                    MessageId = m.MessageId,
                    SenderId = m.SenderId,
                    ReceiverId = m.ReceiverId,
                    Content = m.Content,
                    SendTime = m.SendTime,
                    IsRead = m.IsRead,
                    SenderName = m.Sender.Name,
                    ReceiverName = m.Receiver.Name
                })
                .ToListAsync();
        }
    }
}
